<template>
	<view class="container">
    <view class="navbar">
      <navbar title="加入会员" left=""></navbar>
    </view>
	  <view class="wechatapp">
	    <image src="/static/wechatapp.png"></image>
	  </view>
	  <view class="auth-title">YOMIGO邀您免费入会</view>
	  <view class="auth-subtitle">获得你的公开信息（昵称、头像等）</view>
    <!-- #ifdef MP-WEIXIN || H5 -->
    <button v-if="showGetUserInfoBtn" class="login-btn" openType="getUserInfo" lang="zh_CN" @getuserinfo="authorLogin">同意获取{{text}}授权</button>
    <button v-else class="login-btn" openType="getPhoneNumber" lang="zh_CN" @getphonenumber="getPhoneNumber" :disabled="loginBtnDis">{{text}}用户一键登录</button>
    <!-- #endif -->
	</view>
</template>
<script>
import authApi from "../../utils/auth";
import userApi from "@/api/user.js"
import {mapState} from "vuex"; //引入mapState, mapGetters
export default {
    data() {
        return {
          showGetUserInfoBtn: true,
          loginBtnDis: false,
          text: '',
          showWx: true
        };
    },
    onShow(options) {
      const type = uni.getSystemInfoSync().uniPlatform
      if(type == 'mp-weixin') {
		    this.text = '微信'
	    }
      if(type == 'mp-alipay') {
        this.text = '支付宝'
        this.showWx = false
      }
      // 查看是否获取过授权
      const that = this
      //#ifdef MP-WEIXIN
      uni.getSetting({
        success(res) {
          if (res.authSetting && res.authSetting['scope.userInfo']) {
            that.showGetUserInfoBtn = false
            return
          }
        }
      })
      //#endif

      //#ifdef MP-ALIPAY
      uni.getSetting({
        success(res) {
			    console.log(res)
          if (res.authSetting && res.authSetting['userInfo']) {
			  // 微信授权成功之后，进行获取支付宝用户的信息
			  my.getOpenUserInfo({
			    success: (res) => {
			      console.log('=========getAliOpenUserInfo===========',res)
			      let userInfo = JSON.parse(res.response).response
			      uni.setStorageSync('aliUserInfo',JSON.stringify(userInfo))
			    },
			    fail: (err) => {
			      console.log(err)
			    }
			  });
            that.showGetUserInfoBtn = false
            return
          }
        }
      })
      this.getAliUserId()
      //#endif

      // uni.getProvider({
      //   service: 'oauth',
      //   success: function (res) {
      //     console.log(123213213213123,res.provider)
      //     // 获取用户登录凭证code
      //     uni.login({
      //       provider: res.provider,
      //       success: function (loginRes) {
      //         console.log('uniapp登录凭证',loginRes);
      //         uni.getUserInfo({
      //           provider: 'alipay',
      //           success: function (infoRes) {
      //             console.log('xasxasxasxaxas',infoRes)
      //             console.log('用户昵称为：' + infoRes.userInfo.nickName);
      //           }
      //         });
      //       }
      //     });
      //   }
      // });
    },
  computed: {
    ...mapState({
      table_no: (state) => state.order.table_no,
      branch_uuid: (state) => state.order.branch_uuid,
    }),
    },
    methods: {
      //#ifdef MP-WEIXIN
      /**
       * 获取微信授权
       */
      authorLogin: function (e) {
        if (e.detail.errMsg == 'getUserInfo:ok') {
          this.showGetUserInfoBtn = false
          return false;
        };
        this.showGetUserInfoBtn =  true
      },
      // 获取微信手机号
      async getPhoneNumber (e) {
        let that = this
        if(e.detail.errMsg!='getPhoneNumber:ok') return false
        this.loginBtnDis = true
        // 检测session是否过期
        const checkSessionRes = await this.checkSession()
        if(!checkSessionRes) {
          // 进行微信登陆
          console.log('reload wxLogin')
          const wxLoginRes = await this.wxLogin()
          if(wxLoginRes) {
            console.log('session_key =========>',uni.getStorageSync('session_key'))
            const WxUserInfo = await this.getWxUserInfo()
            await this.getUserToken(e.detail,WxUserInfo)
          }
          return
        }
        const WxUserInfo = await this.getWxUserInfo()
        await this.getUserToken(e.detail,WxUserInfo)

      },

      // 检测微信用户登陆状态是否过期
      checkSession () {
        return new Promise((resolve, reject) => {
          uni.checkSession({
            success(d) {
              console.log('---checkSession未过期 ---','sessionCode===>',uni.getStorageSync('sessionCode'))
              // console.log('sessionCode', uni.getStorageSync('sessionCode'))
              if (!uni.getStorageSync('sessionCode') || uni.getStorageSync('sessionCode').length < 0) {
                // self.wxLogin()
                resolve(false)
                return false
              }
              resolve(true)
              // getUserInfo()
            },
            fail(e) {
              console.log('已经过期')
              console.log(e)
              resolve(false)
            }
          })
        })
      },
      // wx 登陆
      wxLogin () {
        const self = this
        return new Promise((resolve, reject) => {
          uni.login({
            provider: 'weixin',
            success: function(loginRes) {
              console.log('wxlogin =====>',loginRes)
              // 本地缓存 code
              uni.setStorageSync('sessionCode', loginRes.code)

              // 进行获取session_key
              self.getCode2Session().then(res=>{
                if(res){
                  resolve(true)
                  return
                }
                resolve(false)
              })
            },
            fail: function(err) {
              resolve(false)
            }
          })
        })
      },
      // 使用微信登陆code 获取 sessionKey
      getCode2Session() {
        return new Promise((resolve, reject) => {
          userApi.getCode2Session({
            code: uni.getStorageSync('sessionCode'),
          }).then(res => {
            if(res.code == 200){
              console.log('=========getCode2Session======',res)
              uni.setStorageSync('session_key',res.data.session_key)
              console.log('=======session_key=====',uni.getStorageSync('session_key'))
              resolve(true)
              return
            }
            resolve(false)
          })
        })
      },
      // 云端获取微信用户信息
      getWxUserInfo () {
        return new Promise((resolve, reject) => {
          uni.getUserInfo({
            provider: 'weixin',
            success: function (infoRes) {
              console.log('===================',infoRes)
              resolve(infoRes)
            },
            fail: function (err) {
              reject(false)
            }
          });
        })
      },
      /**
       * 进行微信云端登陆
       * @param infoRes  获取手机号返回的信息
       * @param WxUserInfo 获取用户信息
       * @returns {Promise<*>}
       */
      async getUserToken (infoRes,WxUserInfo) {
        return await userApi.login({
          user_info: {
            session_key: uni.getStorageSync('session_key'),
            iv: WxUserInfo.iv,
            encrypted_data: WxUserInfo.encryptedData,
          },
          cellphone_info: {
            session_key: uni.getStorageSync('session_key'),
            iv: infoRes.iv,
            encrypted_data: infoRes.encryptedData,
          },
          type: 1,
          branch_uuid: this.branch_uuid,
          table_no: this.table_no
        }).then(res => {
          if(res.code == 200){
            authApi.setToken(res.data.token)
            uni.navigateBack({
              delta:1,
              success() {
                // 刷新页面数据方法
                uni.$emit('reloadPageData',{msg:'页面更新'})
              }
            })
          }
        })
      },


      // 登陆方法
      async authLogin () {
        const settingRes = await this.getSetting()
        if(!settingRes) return false
        // 检测session是否过期
        const checkSessionRes = await this.checkSession()
        if(!checkSessionRes) {
          // 进行微信登陆
          const wxLoginRes = await this.wxLogin()
          if(wxLoginRes) {
            const WxUserInfo = await this.getWxUserInfo()
            if(WxUserInfo) {
              await this.getUserToken(WxUserInfo)
            }
          }
          return
        }
        const WxUserInfo = await this.getWxUserInfo()
        if(WxUserInfo) {
          await this.getUserToken(WxUserInfo)
        }
      },
      //#endif

      //#ifdef MP-ALIPAY
      // 获取用户userId

      async getAliUserId() {
        const authCode = await this.getAuthCode()
        await userApi.getAliUserId({authCode: authCode}).then(res=>{
			uni.setStorageSync("ALI_USER_ID",res.data.user_id)
			uni.setStorageSync("ALIPAY_USER_ID",res.data.alipay_user_id)
		})
      },
      // 获取用户 authCode
      async getAuthCode() {
        return new Promise((resolve, reject) => {
          my.getAuthCode({
            scopes: 'auth_base',
            success: res => {
              console.log('authCode======',res)
              const authCode = res.authCode;
              resolve(authCode)
            },
            fail: err => {
              reject(err)
              console.log('my.getAuthCode 调用失败', err)
            }
          });
        })
      },
      // 支付宝小程序获取用户信息,发起获取用户信息授权
      getAliOpenUserInfo(res) {
        console.log('getAliOpenUserInfo===========',res)
        my.getOpenUserInfo({
          success: (res) => {
            console.log('=========getAliOpenUserInfo===========',res)
            let userInfo = JSON.parse(res.response).response
            uni.setStorageSync('aliUserInfo',JSON.stringify(userInfo))
          },
          fail: (err) => {
            console.log(err)
          }
        });
        this.showGetUserInfoBtn = false
      },


      // 支付宝小程序用户拒绝授权
      handleAliAuthError(res) {
        // console.log(21321312321321321312)
        console.log('handleAliAuthError',res)
		uni.showModal({
			title: "授权提示",
			content: "取消授权可能会使部分服务无法使用，或者页面信息展示不完整"
		})
      },



      // 支付宝小程序获取手机号
      getAliPhoneNumber(res) {
        console.log('getAliPhoneNumber',res)
        my.getPhoneNumber({
          success: (res) => {
            console.log("getPhoneNumberRes=====",res);
			let response = JSON.parse(res.response)
            let encryptedData = response.response;
			let sign = response.sign;
            let aliUserInfo = uni.getStorageSync("aliUserInfo")
            if (aliUserInfo == null || aliUserInfo == '') {
              this.showGetUserInfoBtn = true
              uni.showToast({
                icon: 'none',
                title: '用户未授权'
              })
              return
            }
            let data = JSON.parse(aliUserInfo)
			data.user_id = uni.getStorageSync("ALI_USER_ID")
			data.ali_pay_user_id = uni.getStorageSync("ALIPAY_USER_ID")
            data.encryptedData = encryptedData
			data.encrypteSign = sign
            //	执行登录
            this.getAliUserToken(data)
          },
          fail: (res) => {
            console.log(res);
            console.log('getPhoneNumber_fail');
          }
        });
      },

      // 支付宝小程序用户拒绝授权手机号
      handleAliPhoneAuthError(res) {
        console.log(21321312321321321312)
        console.log('handleAliAuthError',res)
      },

      /**
       * 进行支付宝云端登陆
       * @param infoRes  获取手机号返回的信息
       * @param WxUserInfo 获取用户信息
       * @returns {Promise<*>}
       */
      async getAliUserToken (UserInfo) {
        return await userApi.login({
          ali_user_info: UserInfo,
          type: 2,
          branch_uuid: this.branch_uuid,
          table_no: this.table_no
        }).then(res => {
          if(res.code == 200){
            authApi.setToken(res.data.token)
            uni.navigateBack({
              delta:1,
              success() {
                // 刷新页面数据方法
                uni.$emit('reloadPageData',{msg:'页面更新'})
              }
            })
          }
        })
      },
      //#endif

    },
};
</script>
<style lang="scss">

.container {
  padding: 0 60rpx;
}

.wechatapp {
  padding: 80rpx 0 48rpx;
  border-bottom: 1rpx solid #e3e3e3;
  margin-bottom: 72rpx;
  text-align: center;
}

.wechatapp image {
  width: 200rpx;
  height: 200rpx;
}

.auth-title {
  color: #585858;
  font-size: 40rpx;
  margin-bottom: 40rpx;
}

.auth-subtitle {
  color: #888;
  margin-bottom: 88rpx;
}

.login-btn {
  border: none;
  height: 88rpx;
  line-height: 88rpx;
  background: #04be01;
  color: #fff;
  font-size: 11pt;
  border-radius: 999rpx;
}

.alipay-btn{
  background: #328cfd
}

.login-btn::after {
  display: none;
}

.login-btn.button-hover {
  box-shadow: inset 0 5rpx 30rpx rgba(0, 0, 0, 0.15);
}

</style>
